<template>
  <div>
    <el-card>
      <!-- 查询 -->
      <el-form :inline="true"  class="demo-form-inline">
  <el-form-item>
    <el-input v-model="pageLimit.username" placeholder="用户名"></el-input>
  </el-form-item>

  <el-form-item>
    <el-button type="primary" @click="onSubmit" icon="el-icon-search">搜索</el-button>
    <el-button  @click="empty">清空</el-button>
  </el-form-item>
</el-form>

<!-- 添加 -->
<el-form>
  <el-form-item>
    <el-button type="primary" size="medium" @click="addT">添加</el-button>
    <el-button type="danger" @click="deleteAllData" :disabled="itemsList.length===0">批量删除</el-button>
  </el-form-item>
</el-form>

<!-- 对话框 -->
<el-dialog title="添加用户" :visible.sync="dialogFormVisible" >
  <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="120px">

    <el-form-item label="用户名" prop="username">
    <el-input v-model="userForm.username"></el-input>
  </el-form-item>

  <el-form-item label="用户昵称">
    <el-input v-model="userForm.nickName"></el-input>
  </el-form-item>

  <el-form-item v-if="!userForm.id" label="用户密码" prop="password">
    <el-input v-model="userForm.password"></el-input>
  </el-form-item>
  
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="cancel">取消</el-button>
    <el-button type="primary" @click="confirmAddUser">确定</el-button>
  </div>
</el-dialog>
<!-- 表格 -->
<el-table
    v-loading="loading"
    ref="multipleTable"
    :data="itemsList"
    border
    tooltip-effect="dark"
    style="width: 100%"
    @selection-change="handleSelectionChange">
    
    <el-table-column
        type="selection"
        width="55" />

      <el-table-column
        type="index"
        label="序号"
        width="80"
        align="center"
      />

    <el-table-column prop="username" label="用户名" width="150"/>
      <el-table-column prop="nickName" label="用户昵称" />
      <el-table-column prop="roleName" label="角色列表" width="200"/>
      
      <el-table-column prop="gmtCreate" label="创建时间" width="180"/>
      <el-table-column prop="gmtModified" label="更新时间" width="180"/>

    <el-table-column prop="operate" width="200" align="center" fixed="right" label="操作">
      <template v-slot="{row}">
      <el-button type="info" icon="el-icon-user-solid" @click="showAssignRole(row)" size="mini" title="分配角色"></el-button>
      <el-button style="margin: 0 15px" type="primary" @click="getupdata(row)" size="mini" icon="el-icon-edit" title="修改用户"></el-button>

     <template>
      <el-popconfirm :title="`确定删除 ${row.username}吗?`" @confirm="deteleUser(row.id)">
        <el-button  slot="reference" type="danger" size="mini" icon="el-icon-delete" title="删除用户"></el-button>
      </el-popconfirm>
    </template>
        
    </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
      :page-sizes="[5,10,29,30]"
      :page-size="pageLimit.limit"
      :current-page="pageLimit.page"
      style="padding: 20px 0;"
      @size-change="handleSizeChange"
      @current-change="getPage"
      layout="prev, pager, next, jumper,->,total,sizes"
      :total="dataTodal.total">
  </el-pagination>
  <!-- 设置角色列表 -->
  <el-dialog title="设置角色" :visible.sync="roleSatte.dialogRoleV" :before-close="resetRoleData">
    <el-form label-width="120px">
      <el-form-item label="用户名" prop="username">
         <el-input disabled v-model="userForm.username"></el-input>
      </el-form-item>

      <el-form-item label="角色列表">
        <el-checkbox :indeterminate="roleSatte.isIndeterminate" v-model="roleSatte.checkAll" @change="handleCheckAllChange">全选</el-checkbox>
  <div style="margin: 15px 0;"></div>
  <el-checkbox-group v-model="roleSatte.userRoleIds" @change="handleCheckedCitiesChange">
    <el-checkbox v-for="items in itemsList" :label="items" :key="items.id">{{items.roleName}}</el-checkbox>
  </el-checkbox-group>
      </el-form-item>
    </el-form>

    <template #footer>
        <el-button type="primary" @click="assignRole">保存</el-button>
        <el-button @click="resetRoleData">取消</el-button>
      </template>
  </el-dialog>
</el-card>
</div>
</template>
<script>
import { mapGetters, mapState } from 'vuex';

// let cityOptions

export default {
  name: 'User',
  data() {
    return {
      //全选全不选
      assignRoles: [],
      roleSatte: {
        dialogRoleV: false,
        // roleLoading: false,
        checkAll: false,
        isIndeterminate: false,
        userRoleIds: [],
        allRoles: []
      },

      deleted: false,
      loading: false,
      // 添加表单 收集数据
      dialogTableVisible: false,
      dialogFormVisible: false,
      dialogForm: false,
      userForm: {
        username: '',
        nickName: '',
        password: ''
      },

      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      form: {
        name: '',
      },
      formLabelWidth: '120px',

      // loading :false,
      // 分页数据
      pageLimit: {
        username: '',
        page: 1,
        limit: 10,
      },
      multipleSelection: []
    }
    //表格数据
  },
  mounted() {
    this.getPageList()
  },
  methods: {
    //分配角色
    showAssignRole(user) {
      this.userForm = user
      let { assignRoles } = this
      assignRoles = this.nikNameList.map(item => item.id)

      this.roleSatte.dialogRoleV = true

      this.$store.dispatch('controller/getId', assignRoles)
    },
    //保存
    assignRole() {
      let userId = this.user?.id
      console.log('cccc');
      this.roleSatte.dialogRoleV = false
      // let roleIds = this.nikNameList.roleName(',')
      this.$store.dispatch('controller/assignUser', userId)
      // await assignUserRoleListApi(userId,roleIds)
      this.$message({
        message: '分配角色成功',
        type: 'success'
      })
      this.resetRoleData()

      // console.log(this.$store.getters.name, this.user)
      // if (this.$store.getters.name===this.user.username) {
      //   window.location.reload()
      // }
    },
    // 取消
    resetRoleData() {
      this.roleSatte.dialogRoleV = false
    },
    //多选框 全选
    handleCheckAllChange(val) {
      // console.log('111',val);
      this.roleSatte.userRoleIds = val ? this.nikNameList.map(item => item.id) : []
      this.roleSatte.checkAll === val
      // console.log(this.roleSatte.checkAll);
      this.roleSatte.isIndeterminate = false;
    },
    //单选
    handleCheckedCitiesChange(val) {
      // console.log('222', val);

      this.roleSatte.checkAll = this.roleSatte.userRoleIds.length === this.nikNameList.map(item => item.id).length;
      this.roleSatte.isIndeterminate = this.roleSatte.userRoleIds.length > 0 && this.roleSatte.userRoleIds.length < this.nikNameList.map(item => item.id).length;
    },
    //表格
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id);
    },
    //拿到列表数据
    getPageList() {
      let _this = this
      let { pageLimit } = _this
      _this.$store.dispatch('controller/getPageList', pageLimit)
    },
    // 搜索
    onSubmit() {
      this.getPageList()
    },
    //清空
    empty() {
      this.pageLimit.username = ''
      this.getPageList()
    },
    //添加
    addT() {
      this.userForm = {
        username: '',
        nickName: '',
        password: ''
      }
      this.dialogTableVisible = true
      this.dialogFormVisible = true
    },
    //点击确定添加数据
    async confirmAddUser() {
      let _this = this
      let { userForm } = this
      if (userForm.id) {
        _this.getupdata(userForm)
        _this.dialogFormVisible = false
        _this.getPageList()
      } else {
        await _this.$store.dispatch('controller/getAddUser', userForm)
        console.log('@@@--->', userForm.id);
        _this.dialogFormVisible = false
        _this.getPageList()
      }

    },
    //修改表单
    async getupdata(userForm) {
      this.userForm = { ...userForm }
      this.dialogFormVisible = true
      await this.$store.dispatch('controller/undata', userForm)
    },
    //点击取消
    cancel() {
      this.dialogFormVisible = false
      this.userForm = {
        username: '',
        nickName: '',
        password: ''
      }
    },
    //点击删除单个
    async deteleUser(id) {
      await this.$store.dispatch('controller/getDeleteOneData', { id })
      this.$message({
        message: '删除成功',
        type: 'success'
      })
      this.getPageList()
    },
    //点击删除多个deleteAllData
    deleteAllData() {
      let { multipleSelection } = this
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        },
          this.$store.dispatch('controller/getAllDeleteData', multipleSelection),
          this.getPageList()
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 分页
    handleSizeChange(val) {
      this.pageLimit.limit = val
      this.getPageList()
    },
    //分页点击
    getPage(val) {
      this.pageLimit.page = val
      this.getPageList()
    }
  },
  computed: {
    ...mapState('controller', ['pageList']),
    ...mapGetters('controller', ['itemsList', 'dataTodal']),
    nikNameList() {
      return (this.pageList.data || {}).items || []
    },
  }
}
</script>

<style lang= 'less' scoped>

</style>
